package com.tuxing.draa_data.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.tuxing.draa_data.common.DraaContent;
import com.tuxing.draa_data.dao.*;
import com.tuxing.draa_data.dao.center.NewDcBibliographyPeriDao;
import com.tuxing.draa_data.dao.center.NewDcBibliographyPeriDetailDao;
import com.tuxing.draa_data.dao.center.NewDcPackageDao;
import com.tuxing.draa_data.dao.center.NewDcPeriDao;
import com.tuxing.draa_data.dao.subject.NewDcSubjectDictDao;
import com.tuxing.draa_data.pojo.*;
import com.tuxing.draa_data.pojo.center.NewDcBibliographyPeri;
import com.tuxing.draa_data.pojo.center.NewDcBibliographyPeriDetail;
import com.tuxing.draa_data.pojo.center.NewDcPackage;
import com.tuxing.draa_data.pojo.center.NewDcPeri;
import com.tuxing.draa_data.pojo.subject.NewDcSubjectDict;
import com.tuxing.draa_data.service.subject.AsyncService;
import com.tuxing.draa_data.util.ConvertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author Lzb
 * @version 1.0
 * @className ChaoXingPeriServiceImpl
 * @description 基础描述:
 * @date 2021/12/1 16:10
 */
@Slf4j
@Service
public class ChaoXingPeriServiceImpl extends ServiceImpl<ChaoXingPeriDao, ChaoXingPeri> implements ChaoXingPeriService {

    @Autowired
    private ChaoXingPeriDao chaoXingPeriDao;

    @Resource
    private ChaoxingPackageDao chaoxingPackageDao;

    @Resource
    private NewDcPackageDao newDcPackageDao;

    @Resource
    private NewDcPeriDao newDcPeriDao;

    @Resource
    private CnkiYshDao cnkiYshDao;

    @Override
    public void saveCnkiJournal() {
        List<CnkiYsh> cnkiYshList = cnkiYshDao.selectList(null);
        for (CnkiYsh cnkiYsh : cnkiYshList) {
            try {
                String lang = cnkiYsh.getLang();
                if (!lang.contains("中文")) {
                    continue;
                }
                Long recordIdByCnKi = getRecordIdByCnKi(cnkiYsh);
                String years = cnkiYsh.getYears();
                List<Integer> yearList = Lists.newArrayList();
                String[] split = years.split(";");
                for (String s : split) {
                    int year = ConvertUtil.objToInt(s, 2022);
                    yearList.add(year);
                }
                Integer max = Collections.max(yearList);
                Integer min = Collections.min(yearList);
                String yearRange = min + "-" + max;


                NewDcPeri oneByBidDidPidYear = newDcPeriDao.findOneByBidDidPidYear(recordIdByCnKi, 1466399814573551621L, 1466399814573551633L, 2022);
                if (oneByBidDidPidYear != null) {
                    continue;
                }

                NewDcPeri newDcPeri = new NewDcPeri();
                newDcPeri.createByCnki(1466399814573551621L, 1466399814573551633L, recordIdByCnKi,
                        2022, min.toString(), max.toString(), yearRange, cnkiYsh.getUrl(), 3, 0, 0, 1);
                newDcPeriDao.insert(newDcPeri);
            } catch (Exception ex) {
                log.error("保存期刊错误，错误数据：" + cnkiYsh);
                log.error("错误原因：" + ex.getMessage(), ex);
            }
        }
    }

    private Long getRecordIdByCnKi(CnkiYsh cnkiYsh) {
        String cn = cnkiYsh.getCn();
        String issn = cnkiYsh.getIssn();
        String name = cnkiYsh.getName();


        if (!Strings.isNullOrEmpty(issn)) {
            NewDcBibliographyPeri oneByPISSN = newDcBibliographyPeriDao.findOneByPISSN(issn, 3);
            if (oneByPISSN != null) {
                Long recordId = oneByPISSN.getRecordId();
                updateJournal(oneByPISSN, cnkiYsh);
                updateJournalDetail(recordId, cnkiYsh);
                return recordId;
            }
        }

        if (!Strings.isNullOrEmpty(cn)) {
            NewDcBibliographyPeri oneByCN = newDcBibliographyPeriDao.findOneByCN(cn);
            if (oneByCN != null) {
                Long recordId = oneByCN.getRecordId();
                updateJournal(oneByCN, cnkiYsh);
                updateJournalDetail(recordId, cnkiYsh);
                return recordId;
            }
        }

        NewDcBibliographyPeri cnOneByTitle = newDcBibliographyPeriDao.findCnOneByTitle(name, 3);
        if (cnOneByTitle != null) {
            Long recordId = cnOneByTitle.getRecordId();
            updateJournal(cnOneByTitle, cnkiYsh);
            updateJournalDetail(recordId, cnkiYsh);
            return recordId;
        } else {
            return addJournal(cnkiYsh);
        }
    }

    private Long addJournal(CnkiYsh cnkiYsh) {
        NewDcBibliographyPeri peri = new NewDcBibliographyPeri();
        peri.setSource(0);
        peri.setTitle(cnkiYsh.getName());
        peri.setMdType("CNMARC");
        peri.setLangCode(3);
        peri.setTransTitle(cnkiYsh.getEnName());
        peri.setAlternateTitle(cnkiYsh.getOldName());
        peri.setPublisher(cnkiYsh.getPub());
        peri.setPIssn(cnkiYsh.getIssn());
        peri.setPeriCnNo(cnkiYsh.getCn());
        newDcBibliographyPeriDao.insert(peri);

        NewDcBibliographyPeriDetail periDetail = new NewDcBibliographyPeriDetail();
        periDetail.setCoverUrl(cnkiYsh.getCover());
        periDetail.setPubYear(cnkiYsh.getCreateYear());
        periDetail.setPubLoc(cnkiYsh.getAddress());
        periDetail.setOa("0");
        periDetail.setRecordId(peri.getRecordId());
        newDcBibliographyPeriDetailDao.insert(periDetail);

        return peri.getRecordId();
    }

    private void updateJournal(NewDcBibliographyPeri peri, CnkiYsh cnkiYsh) {
        peri.setPublisher(cnkiYsh.getPub());
        peri.setTransTitle(cnkiYsh.getEnName());
        peri.setAlternateTitle(cnkiYsh.getOldName());
        newDcBibliographyPeriDao.updateById(peri);
    }

    private void updateJournalDetail(Long recordId, CnkiYsh cnkiYsh) {
        NewDcBibliographyPeriDetail periDetail = newDcBibliographyPeriDetailDao.selectById(recordId);
        if (periDetail == null) {
            periDetail = new NewDcBibliographyPeriDetail();
            periDetail.setCoverUrl(cnkiYsh.getCover());
            periDetail.setPubYear(cnkiYsh.getCreateYear());
            periDetail.setPubLoc(cnkiYsh.getAddress());
            periDetail.setRecordId(recordId);
            periDetail.setOa("0");
            newDcBibliographyPeriDetailDao.insert(periDetail);
        } else {
            periDetail.setCoverUrl(cnkiYsh.getCover());
            periDetail.setPubYear(cnkiYsh.getCreateYear());
            periDetail.setPubLoc(cnkiYsh.getAddress());
            newDcBibliographyPeriDetailDao.updateById(periDetail);
        }

    }

    @Override
    public List<ChaoXingPeri> findAllData() {
        return chaoXingPeriDao.findAllData();
    }

    @Resource
    private ChaoxingPuDao chaoxingPuDao;

    @Resource
    private NewDcCjPuDao newDcCjPuDao;

    @Resource
    private NewDcSubjectDictDao newDcSubjectDictDao;

    @Resource
    private NewDcBibliographyPeriDao newDcBibliographyPeriDao;

    @Resource
    private NewDcBibliographyPeriDetailDao newDcBibliographyPeriDetailDao;

    /**
     * @return 暂无返回结果
     * @descpription 保存超星期刊数据
     * @author yuanshihang
     * @date 2022/3/31 14:45
     * @Version 1.0
     */
    @Override
    public void saveChaoXingPeri() {
        List<ChaoxingPackage> chaoXingPackage = chaoxingPackageDao.findChaoXingPackage();
        for (ChaoxingPackage chaoxingPackage : chaoXingPackage) {

            Integer resourceId = chaoxingPackage.getResourceId();
            Integer resourcePackageId = chaoxingPackage.getResourcePackageId();

            NewDcPackage newDcPackage = new NewDcPackage();
            try {
                newDcPackage.create(ConvertUtil.objToLong(resourceId), resourcePackageId.toString(), chaoxingPackage.getResourcePackageName(), null, DraaContent.OrderSource.FROM_CHAOXING);
                newDcPackageDao.insert(newDcPackage);
            } catch (Exception ex) {
                log.error("保存新资源包信息错误，错误原因：" + ex.getMessage(), ex);
                continue;
            }
            Long packageId = newDcPackage.getPackageId();

            QueryWrapper<ChaoXingPeri> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("resource_id", resourceId).eq("resource_package_id", resourcePackageId);
            List<ChaoXingPeri> chaoXingPeris = chaoXingPeriDao.selectList(queryWrapper);

            for (ChaoXingPeri xingPeris : chaoXingPeris) {
                try {
                    NewDcPeri newDcPeri = new NewDcPeri();
                    newDcPeri.createByCx(xingPeris, packageId);
                    newDcPeriDao.insert(newDcPeri);
                } catch (Exception ex) {
                    log.error("保存新资源库包资源信息错误，错误原因：" + ex.getMessage(), ex);
                }
            }
        }
    }

//    @Resource
//    private NewDcBibliographyPeriDao newDcBibliographyPeriDao;
//
//    @Resource
//    private NewDcBibliographyPeriDetailDao newDcBibliographyPeriDetailDao;

    @Resource
    private AsyncService asyncService;

    /**
     * @return 暂无返回数据
     * @descpription 进行超星电子资源期刊数据的更新和元数据保存
     * @author yuanshihang
     * @date 2022/4/8 11:09
     * @Version 1.0
     */
    @Override
    public void updateChaoXingPeri() {
        asyncService.doChaoXingPeri("super-1", 0, 1000);
        asyncService.doChaoXingPeri("super-2", 1000, 1000);
        asyncService.doChaoXingPeri("super-3", 2000, 1000);
        asyncService.doChaoXingPeri("max-4", 3000, 1000);
        asyncService.doChaoXingPeri("max-5", 4000, 1000);
        asyncService.doChaoXingPeri("max-6", 5000, 1000);
        asyncService.doChaoXingPeri("human-7", 6000, 2000);
        try {
            Thread.sleep(9000000000000000000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void parseChinaPuCnJournal() {
        List<ChaoxingPu> chaoxingPuList = chaoxingPuDao.selectList(null);
        for (ChaoxingPu chaoxingPu : chaoxingPuList) {
            Long recordId = findPeriId(chaoxingPu);

            String two = chaoxingPu.getTwo();
            QueryWrapper<NewDcSubjectDict> subWrapper = new QueryWrapper<>();
            subWrapper.eq("SUB_TYPE", 31);
            if (!Strings.isNullOrEmpty(two)) {
                subWrapper.eq("SUB_VALUE", two);
            } else {
                subWrapper.eq("SUB_VALUE", chaoxingPu.getOne());
            }
            subWrapper.last("limit 1");
            System.out.println(chaoxingPu.toString());
            NewDcSubjectDict newDcSubjectDict = newDcSubjectDictDao.selectOne(subWrapper);
            Long subId = newDcSubjectDict.getSubId();
            Long parentSubId = newDcSubjectDict.getParentSubId();

            NewDcCjPu newDcCjPu = new NewDcCjPu();
            newDcCjPu.create(recordId, subId, chaoxingPu.getYear(), parentSubId);
            newDcCjPuDao.insert(newDcCjPu);
        }
    }

    private Long findPeriId(ChaoxingPu chaoxingPu) {
        String pissn = chaoxingPu.getPissn();
        if (!Strings.isNullOrEmpty(pissn) && !pissn.equals("NULL")) {
            QueryWrapper<NewDcBibliographyPeri> issnWrapper = new QueryWrapper<>();
            issnWrapper.eq("P_ISSN", pissn).eq("LANG_CODE", 3);
            issnWrapper.last("limit 1");
            NewDcBibliographyPeri peri = newDcBibliographyPeriDao.selectOne(issnWrapper);
            if (peri != null) {
                return peri.getRecordId();
            }
        } else {
            pissn = null;
        }
        String cn = chaoxingPu.getCn();
        if (!Strings.isNullOrEmpty(cn) && !cn.equals("NULL")) {
            QueryWrapper<NewDcBibliographyPeri> cnWrapper = new QueryWrapper<>();
            cnWrapper.eq("PERI_CN_NO", cn).eq("LANG_CODE", 3);
            cnWrapper.last("limit 1");
            NewDcBibliographyPeri peri = newDcBibliographyPeriDao.selectOne(cnWrapper);
            if (peri != null) {
                return peri.getRecordId();
            }
        } else {
            cn = null;
        }
        String title = chaoxingPu.getTitle();
        if (!Strings.isNullOrEmpty(title)) {
            QueryWrapper<NewDcBibliographyPeri> titleWrapper = new QueryWrapper<>();
            titleWrapper.eq("TITLE", title).eq("LANG_CODE", 3);
            titleWrapper.last("limit 1");
            NewDcBibliographyPeri peri = newDcBibliographyPeriDao.selectOne(titleWrapper);
            if (peri != null) {
                return peri.getRecordId();
            }
        }
        NewDcBibliographyPeri peri = new NewDcBibliographyPeri();
        peri.setTitle(title);
        peri.setPIssn(pissn);
        peri.setPeriCnNo(cn);
        peri.setLangCode(3);
        peri.setCreateBy(-1);
        peri.setCreateDate(LocalDateTime.now());
        peri.setUpdateBy(-1);
        peri.setUpdateDate(LocalDateTime.now());
        newDcBibliographyPeriDao.insert(peri);
        return peri.getRecordId();
    }


}
